// 使用 CommonJS 导出函数
const moment = require("moment")
const axios = require('axios');
exports.searchQuery = (tableName, searchParams, page, limit) => {
    let conditions = [];
    let sqlCount = `SELECT COUNT(*) AS total FROM ${tableName} WHERE `;
    let sqlQuery = `SELECT * FROM ${tableName} WHERE `;

    // 遍历 searchParams 对象
    for (const key in searchParams) {
        if (searchParams.hasOwnProperty(key) && searchParams[key] !== undefined && searchParams[key] !== null) {
            let value = searchParams[key];
            if (!value) {
                value = null;
            }
            let condition;
            let regex = /^\d{4}-\d{2}-\d{2}$/;
            // 处理特殊字符，例如 `^`
            if (typeof value === 'string' && value.startsWith('^')) {
                condition = `${key} LIKE '%${value}%'`; // 拼接 SQL
            } else if (key.includes('time') && Array.isArray(value)) {
                condition = `${key} > '${value[0]}' AND ${key} < '${value[1]}'`
            } else {
                condition = `${key} = '${value}'`; // 拼接 SQL
            }
            conditions.push(condition);
        }
    }

    // 构建 WHERE 子句
    if (conditions.length > 0) {
        sqlQuery += conditions.join(' AND ');
        sqlCount += conditions.join(' AND ');
    } else {
        sqlQuery += '1=1'; // 默认条件，当没有过滤条件时
        sqlCount += '1=1';
    }

    // 添加 LIMIT 和 OFFSET 用于分页

    sqlQuery += ` LIMIT ${page - 1},${limit}`;

    // 输出 SQL 查询语句以便调试
    // 返回查询和计数的 SQL 语句
    return { sqlQuery, sqlCount };
};
exports.errorParams = (params = {}, requireParams = []) => {
    //针对参数报错返回结果
    const isError = requireParams.every(item => {
        return params.hasOwnProperty(item)
    })
    return isError;
}
//modeName, agency_name
exports.generateSerialNumbers = (start_sn, end_sn, modelObj, companyCharacteristic) => {
    const regex = /\d{6}$/;
    const startNum = start_sn.match(regex)[0];
    const endNum = end_sn.match(regex)[0];

    // 生成序列号数组   
    const serialNumbers = [];
    for (let i = startNum; i <= endNum; i++) {
        const serialNumber = `${companyCharacteristic}${i}`;
        serialNumbers.push({
            SN: serialNumber,
            model: modelObj.modelId,
            agency_id: modelObj.agency_id,
            store_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            payee_name: "-",//公众号登录后 得到 绑定商户名
            bind_time: '', //公众号登录后 得到绑定时间
            is_active: '2',//公众号上开了998 激活状态变为已激活--
            is_participate: "2",//公众号上开了998之后 就参与了活动 2 未参与。1 参与
            active_time: "", //机器刷够 标准数额，变为已经激活，支付公司推
            bind_status: "2" // 公众号客户登录之后 就是绑定

        });
    }
    return serialNumbers;
}
exports.checkSNExists = async (dataItems, ctx) => {
    /**
     * 检查数据库中是否存在特定的 SN 值
     * @param {Array} dataItems - 包含 SN 值的数组
     * @param {ctx} 实例对象
     * @return {Promise<Object>} - 包含状态和数据的 Promise 对象
     */
    const snList = dataItems.map(item => item.SN);
    const query = 'SELECT SN FROM machine_warehousing WHERE SN IN (?)';
    try {
        // 执行查询
        const results = await ctx.app.mysql.query(query, [snList]);
        const existSNs = [];
        // 过滤出已存在的 SN
        results.forEach(row => {
            if (snList.includes(row.SN)) {
                existSNs.push(row.SN);
            }
        });
        // 根据是否存在 SN 返回不同的结果
        if (existSNs.length > 0) {
            return { status: true, data: existSNs };
        } else {
            return { status: false, data: "" };
        }
    } catch (error) {
        // 处理查询错误
        ctx.logger.error('Database query error:', error);
        throw error;
    }
}

exports.getAccessToken = async () => {
    const appId = "wx510e698c9a72488e";
    const appSecret = "e49d228b53e8380a925b3ab7a7071460"
    const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`);
    return response.data.access_token;
};